/**
 * @method [获取当前cookie,返回obj]
 * @param   null  [无参数]
 * @return  {[object]}[cookie值]
 */
export function getCookiAll() {
  const obj = {} as {
    [index: string]: string
  }
  let strCooki: string | any[] = document.cookie
  strCooki = strCooki.split('; ')
  for (let i = 0; i < strCooki.length; i += 1) {
    const arr: string[] = strCooki[i].split('=')
    const [key, value] = arr
    obj[key] = value
  }
  return obj
}

/**
 * @method [获取想要的kooki名称对应值]
 * @param   {[string]}  name  [想要获取的cooki名称]
 * @return  {[string]}        [return description]
 */
export function getCooki(name: string) {
  const obj = getCookiAll()
  return obj[name]
}

/**
 * @method [设置cookie]
 * @param   {[string]}  name    [想要设置的cookie名称]
 * @param   {[string]}  value   [想要设置的cookie内容]
 * @param   {[number]}  day     [cookie想保存的日期(天数)]
 * @param   {[string]}  path    [cookie路径权限]
 * @param   {[string]}  domain  [cookie域名]
 * @param   {[string]}  secure  [安全性,输入任何表示开启安全]
 * @returns null | error [成功返回null,失败返回错误信息]
 */
export function setCooki(name: string, value: string, day?: number, path?: string, domain?: string, secure?: string): unknown | null {
  try {
    let str = ''
    if (name) {
      str += `${name}=${value};`
    }
    if (day) {
      const date = new Date()
      date.setDate(date.getDate() + day)
      str += `expires=${date.toUTCString()};`
    }
    if (path) {
      str += `path=${path};`
    }
    if (domain) {
      str += `domain=${domain};`
    }
    if (secure) {
      str += 'secure;'
    }
    document.cookie = str
  } catch (error) {
    return error
  }
  return null
}

/**
 * @method [删除对应名称cookie]
 * @param   {[str]}  name  [想要删除的cookie名]
 * @return  null | error [成功返回null,失败返回错误信息]
 */
export function delCooki(name: string) {
  return setCooki(name, '', -1)
}
